<template>
  <div v-if="notifyList.length > 0" class="vab-ad">
    <el-carousel
      height="30px"
      direction="vertical"
      :autoplay="true"
      :interval="3000"
      indicator-position="none"
    >
      <el-carousel-item v-for="(item, index) in notifyList" :key="index">
        <el-tag type="success">公告</el-tag>
        <span>{{ item.title }}</span>
      </el-carousel-item>
    </el-carousel>
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

export default {
  data() {
    return {
      stompClient: undefined,
      notifyList: []
    }
  },
  created() {
    this.$nextTick(() => {
      this.receiveNotify()
      window.addEventListener('beforeunload', e => this.closeSocket(e))
    })
  },
  methods: {
    receiveNotify() {
      this.$http.get('/ws/startPollMessage', {
        params: {
          type: 'notify'
        }
      }).then(response => {
        this.openSocket()
      }).catch(e => {})
    },
    openSocket() {
      if (this.stompClient === undefined) {
        const socket = new SockJS(this.$store.state.app.server_api + '/ws/stomp')
        // 使用STMOP子协议的WebSocket客户端
        this.stompClient = Stomp.over(socket)
        const headers = {
          pbuss: getToken()
        }
        let user = this.$store.getters.user
        if (!user) {
          user = {
            userId: 'anonymous'
          }
        }

        // 连接WebSocket服务端
        this.stompClient.connect(headers, (frame) => {
          this.stompClient.subscribe('/user/' + user.userId + '/queue/getNotify', (event) => {
            const list = JSON.parse(event.body)
            this.notifyList = []
            if (list.length > 0) {
              list.forEach(message => {
                this.notifyList.push({
                  id: message.messageId,
                  title: message.title,
                  timeBefore: message.timeBefore,
                  done: false
                })
              })
            }
          }, headers)
        }, e => {})
      }
    },
    closeSocket() {
      this.$http.get('/ws/stopPollMessage', {
        params: {
          type: 'notify'
        }
      }).then(response => {}).catch(e => {})

      if (this.stompClient !== undefined) {
        this.stompClient.disconnect()
        this.stompClient = undefined
      }
    }
  }
}
</script>
<style lang="scss" scoped>
  .vab-ad {
    height: 30px;
    padding-right: 5px;
    padding-left: 5px;
    line-height: 30px;
    cursor: pointer;
    background: #eef1f6;
    box-shadow: 0 -1px 2px rgba(0, 21, 41, 0.08) inset;

    a {
      color: #999;
    }
  }
</style>
